/**
 * WebSocket客户端
 *
 * @author mjy
 * @date 2019-04-21
 */

import packetCode from './PacketCodeC'
// import router from '../router'

let client
let eventDispatcher

const EventDispatcher = function () {
  this.listeners = {}
}

const socket = {
  close: function () {
    if (client !== undefined && client.readyState === WebSocket.OPEN) {
      client.close()
    }
  },
  open: function () {
    // 构造方法
    eventDispatcher = new EventDispatcher()
    // 参数就是与服务器连接的地址
    client = new WebSocket('ws://156.245.160.20:9999/chat')

    // 指定接收二进制数据类型
    client.binaryType = 'arraybuffer'

    // 接收到消息
    client.onmessage = function (event) {
      // 解码
      let responsePacket = packetCode.decode(event.data)

      // 显示指令，只是用于调试
      // showCommand(responsePacket.command)

      // 派发接收数据事件
      eventDispatcher.dispatchEvent(responsePacket.command, toJSON(responsePacket))
    }

    // 连接建立
    client.onopen = function (event) {
    }

    // 连接关闭
    client.onclose = function (event) {
    }

    // 连接发生错误
    client.onerror = function (event) {
    }
  },
  /**
   * 登录
   * @param username 用户名
   * @param password 密码
   */
  login: (username, password, code, func) => {
    let requestPacket = {
      username,
      password,
      code: code,
      version: 1,
      command: 1
    }
    send(requestPacket)
    eventDispatcher.addListener('2', func)
  },

  heartTest: (func) => {
    let requestPacket = {
      version: 1,
      command: 17
    }
    send(requestPacket)
    eventDispatcher.addListener('18', func)
  },

  sendToGroup: (toGroupId, userId, message, msgType, func) => {
    let requestPacket = {
      toGroupId,
      userId,
      msgType,
      message,
      version: 1,
      command: 15
    }
    send(requestPacket)
    eventDispatcher.addListener('16', func)
  },
  sendToFriend: (toUserId, userId, message, msgType, func) => {
    let requestPacket = {
      userId,
      toUserId,
      msgType,
      message,
      version: 1,
      command: 3
    }
    send(requestPacket)
    eventDispatcher.addListener('4', func)
  },

  /**
   * 退出登录
   */
  logout: (userId, func) => {
    let requestPacket = {
      userId,
      version: 1,
      command: 5
    }
    send(requestPacket)
    eventDispatcher.addListener('6', func)
  },

  /**
   * 创建群组
   * @param userIdList 用户userId列表，多个以英文,分割
   */
  createGroup: (userIdList) => {
    let requestPacket = {
      userIdList: userIdList.split(','),
      version: 1,
      command: 7
    }
    send(requestPacket)
  },

  /**
   * 群组内成员列表
   * @param groupId 群组ID
   */
  getGroupMembers: (groupId, userId, func) => {
    let requestPacket = {
      groupId,
      userId,
      version: 1,
      command: 9
    }
    send(requestPacket)
    eventDispatcher.addListener('10', func)
  },

  getLastMessage: (id, chatId, userId, chatType, func) => {
    let requestPacket = {
      id: id,
      chatId,
      userId,
      chatType,
      version: 1,
      command: 45
    }
    send(requestPacket)
    eventDispatcher.addListener('46', func)
  },

  /**
   * 加入群组
   * @param groupId 群组ID
   */
  joinGroup: (groupId) => {
    let requestPacket = {
      groupId,
      version: 1,
      command: 11
    }
    send(requestPacket)
  },

  /**
   * 退出群组
   * @param groupId
   */
  quitGroup: (groupId) => {
    let requestPacket = {
      groupId,
      version: 1,
      command: 13
    }
    send(requestPacket)
  },

  getGroups: (condition, userId, func) => {
    let requestPacket = {
      condition,
      userId,
      version: 1,
      command: 25
    }
    send(requestPacket)
    eventDispatcher.addListener('26', func)
  },

  getFriendMessages: (toUserId, userId, pageNum, func) => {
    let requestPacket = {
      userId,
      pageNum,
      toUserId,
      pageSize: 10,
      version: 1,
      command: 27
    }
    send(requestPacket)
    eventDispatcher.addListener('28', func)
  },
  getFriendMessageByCondition: (toUserId, userId, pageNum, condition, func) => {
    let requestPacket = {
      userId,
      condition,
      pageNum,
      toUserId,
      pageSize: 5,
      version: 1,
      command: 27
    }
    send(requestPacket)
    eventDispatcher.addListener('28', func)
  },
  getGroupMessages: (toGroupId, userId, pageNum, func) => {
    let requestPacket = {
      toGroupId,
      pageNum,
      pageSize: 10,
      userId,
      version: 1,
      command: 23
    }
    send(requestPacket)
    eventDispatcher.addListener('24', func)
  },
  getGroupMessageByCondition: (toGroupId, userId, pageNum, condition, func) => {
    let requestPacket = {
      toGroupId,
      pageNum,
      condition,
      pageSize: 5,
      userId,
      version: 1,
      command: 23
    }
    send(requestPacket)
    eventDispatcher.addListener('24', func)
  },

  /**
   * 聊天列表
   */
  chats: (condition, userId, func) => {
    let requestPacket = {
      condition,
      userId,
      version: 1,
      command: 19
    }
    send(requestPacket)
    eventDispatcher.addListener('20', func)
  },
  updateNickName: (userId, nickName, func) => {
    let requestPacket = {
      userId,
      nickName,
      method: 0,
      version: 1,
      command: 21
    }
    send(requestPacket)
    eventDispatcher.addListener('22', func)
  },

  getUserRemark: (userId, friendUserId, func) => {
    let requestPacket = {
      friendUserId,
      userId,
      method: 10,
      version: 1,
      command: 21
    }
    send(requestPacket)
    eventDispatcher.addListener('22', func)
  },
  updateAvatar: (userId, avatar, func) => {
    let requestPacket = {
      userId,
      avatar,
      method: 0,
      version: 1,
      command: 21
    }
    send(requestPacket)
    eventDispatcher.addListener('22', func)
  },
  deleteGroupMsg: (userId, chatId, func) => {
    let requestPacket = {
      userId,
      chatId,
      method: 5,
      version: 1,
      command: 21
    }
    send(requestPacket)
    eventDispatcher.addListener('22', func)
  },
  deleteFriendMsg: (userId, chatId, func) => {
    let requestPacket = {
      userId,
      chatId,
      method: 6,
      version: 1,
      command: 21
    }
    send(requestPacket)
    eventDispatcher.addListener('22', func)
  },
  updateRemarkName: (userId, friendUserId, remarkName, func) => {
    let requestPacket = {
      userId,
      friendUserId,
      remarkName,
      method: 7,
      version: 1,
      command: 21
    }
    send(requestPacket)
    eventDispatcher.addListener('22', func)
  },
  updatePassword: (username, password, func) => {
    let requestPacket = {
      username,
      password,
      method: 8,
      version: 1,
      command: 21
    }
    send(requestPacket)
    eventDispatcher.addListener('22', func)
  },
  uploadContact: (name, phone, userId, func) => {
    let requestPacket = {
      name,
      phone,
      userId,
      method: 9,
      version: 1,
      command: 21
    }
    send(requestPacket)
    eventDispatcher.addListener('22', func)
  },
  freshCode: (func) => {
    let requestPacket = {
      method: 4,
      version: 1,
      command: 21
    }
    send(requestPacket)
    eventDispatcher.addListener('22', func)
  },
  deleteChatById: (userId, chatId, func) => {
    let requestPacket = {
      userId,
      chatId,
      method: 3,
      version: 1,
      command: 21
    }
    send(requestPacket)
    eventDispatcher.addListener('22', func)
  },
  updateGroupNick: (userId, groupId, nickName, func) => {
    let requestPacket = {
      userId,
      groupId,
      nickName,
      method: 1,
      version: 1,
      command: 21
    }
    send(requestPacket)
    eventDispatcher.addListener('22', func)
  },
  updateGroupName: (userId, groupId, groupName, func) => {
    let requestPacket = {
      userId,
      groupId,
      method: 2,
      groupName,
      version: 1,
      command: 21
    }
    send(requestPacket)
    eventDispatcher.addListener('22', func)
  },
  openChat: (chatId, userId, chatType, func) => {
    let requestPacket = {
      userId,
      chatId,
      chatType,
      version: 1,
      command: 39
    }
    send(requestPacket)
    eventDispatcher.addListener('40', func)
  },
  getMoneys (userId, pageNum, func) {
    let requestPacket = {
      pageNum,
      pageSiz: 5,
      userId,
      version: 1,
      command: 41
    }
    send(requestPacket)
    eventDispatcher.addListener('42', func)
  },
  queryNotice (groupId, func) {
    let requestPacket = {
      groupId,
      action: 'query',
      version: 1,
      command: 43
    }
    send(requestPacket)
    eventDispatcher.addListener('44', func)
  },
  updateNotice (groupId, context, func) {
    let requestPacket = {
      groupId,
      action: 'update',
      context,
      version: 1,
      command: 43
    }
    send(requestPacket)
    eventDispatcher.addListener('44', func)
  }
}

function toJSON (packet) {
  return JSON.parse(JSON.stringify(packet))
}

/**
 * 添加监听器
 * @param eventKey
 * @param fun
 * @param context
 * @returns {{func: *, context: *}}
 */
EventDispatcher.prototype.addListener = function (eventKey, fun, context) {
  let list = []
  this.listeners[eventKey] = list
  let listener = {
    func: fun,
    context: context
  }
  list.push(listener)
  return listener
}

/**
 * 移除监听器
 * @param eventKey
 * @param fun
 * @param context
 */
EventDispatcher.prototype.removeListener = function (eventKey, fun, context) {
  let list = this.listeners[eventKey]
  if (list !== undefined) {
    let size = list.length
    for (let i = 0; i < size; i++) {
      let listener = list[i]
      if (listener.func === fun && listener.context === context) {
        list.splice(i, 1)
        return
      }
    }
  }
}

/**
 * 给监听器派发事件
 * @param eventKey
 * @param event
 */
EventDispatcher.prototype.dispatchEvent = function (eventKey, event) {
  let list = this.listeners[eventKey]
  if (list !== undefined) {
    let size = list.length
    for (let i = 0; i < size; i++) {
      let listener = list[i]
      let fun = listener.func
      let context = listener.context
      if (context != null) {
        fun.call(context, event)
      } else {
        fun(event)
      }
    }
  }
}
/**
 * 命令
 * @param command
 */
// let showCommand = (command) => {
//   let funStr = ''
//   switch (command) {
//     case 2:
//       funStr = '登录'
//       break
//     case 4:
//       funStr = '一对一消息'
//       break
//     case 6:
//       funStr = '退出登录'
//       break
//     case 8:
//       funStr = '创建群组'
//       break
//     case 10:
//       funStr = '群组成员列表'
//       break
//     case 12:
//       funStr = '加入群组'
//       break
//     case 14:
//       funStr = '退出群组'
//       break
//     case 16:
//       funStr = '群消息'
//       break
//     case 18:
//       funStr = '心跳检测回应'
//       break
//     case 20:
//       funStr = '聊天列表'
//       break
//     case 24:
//       funStr = '聊天记录'
//       break
//     case 26:
//       funStr = '群列表'
//       break
//     default:
//       break
//   }
//   console.log(funStr)
// }

/**
 * 发送
 * @param packet
 */
let send = (requestPacket) => {
  if (!window.WebSocket) {
    alert('当前浏览器不支持WebSocket')
    return
  }
  // 当websocket状态打开
  if (client !== undefined && client.readyState === WebSocket.OPEN) {
    client.send(packetCode.encode(requestPacket))
  } else {
    socket.open()
  }
}

export default socket
